#!/usr/bin/env python
# -*- coding: utf-8 -*-


from flask import Flask, request, Response, render_template
import json
import time
import os

app = Flask(__name__, static_url_path='/accounts')

def checkkey(keys, inkeys):
    exclude_keys=[]
    for key in keys:
        if key in inkeys:
            continue
        else:
            exclude_keys.append(key)
    return exclude_keys
'''
@app.after_request
def after(response):
    response.headers['Content-Type'] = 'application/json'
    return response
'''
#{'Content-Type': 'application/json'}
@app.route('/')
def index():
    return render_template('index.html'),200,{'Content-Type': 'text/html'}

    return "<h1>Gasmeter Web Server</h1>" \
           "<p>REST API:</p>" \
           "<ul>" \
           "<li>GET/POST&emsp;/accounts&emsp;#获取所有用户信息/新建用户</li>" \
           "<li>GET/DELETE/PUT&emsp;/accounts/&lt;accountid>&emsp;#获取accountid用户信息/删除accountid用户/更新accountid用户信息</li>" \
           "<li>POST&emsp;/accounts/&lt;accountid>/recharge&emsp;#accountid用户充值</li>" \
           "</ul>", 200,{'Content-Type': 'text/html'}


@app.route('/accounts', methods=['POST', 'GET'])
def accounts():
    if request.method == 'GET':
        acs = {
            "code": 0,
            "message": "success",
            "accounts": []
        }
        for root, dir, fs in os.walk('./accounts'):
            for f in fs:
                acs["accounts"].append(json.load(open(os.path.join(root, f))))
        return json.dumps(acs, indent=2),200,{'Content-Type': 'application/json'}
    elif request.method == 'POST':

        needkeys = ["accountId", "customerId", "gasMeterId", "cycleVolume", "familyMemberNum", "pricePolicyId",
                    "balance"]

        try:
            needkeys = checkkey(needkeys, request.json.keys())
        except:
            return json.dumps({
                "code": -1,
                "message": "Body format error: need a json body and has key %s"%(needkeys)
            }, indent=2),200,{'Content-Type': 'application/json'}
        else:
            if needkeys:
                return json.dumps({
                    "code": -1,
                    "message": "Body format error: need a json body and has key %s"%(needkeys)
                }, indent=2),200,{'Content-Type': 'application/json'}

        accountid = request.json.get('accountId')
        json.dump(request.json, open('./accounts/%s' % (accountid), 'w+'), indent=2)

        return json.dumps({
            "code": 0,
            "message": "create success",
            "createdAt": time.ctime(),
            "updatedAt": time.ctime(),
            "status": "normal"
        }, indent=2),201,{'Content-Type': 'application/json'}


@app.route('/accounts/<string:accountid>', methods=['DELETE', 'GET', 'PUT'])
def accounts_del(accountid):
    data_file = os.path.join('./accounts', accountid)
    if not os.path.exists(data_file):
        return json.dumps({
            "code": 0,
            "message": "accountId [%s] is not exist" % (accountid),
            "accountId": accountid,
            "updatedAt": time.ctime(),
            "status": "normal"
        }, indent=2),200,{'Content-Type': 'application/json'}

    if request.method == 'GET':
        return json.dumps({
            "code": 0,
            "message": "success",
            "account": json.load(open(data_file)),
            "updatedAt": time.ctime(),
            "status": "normal"
        }, indent=2),200,{'Content-Type': 'application/json'}

    elif request.method == 'PUT':
        havekeys = []
        try:
            havekeys = request.json.keys()
        except:
            return json.dumps({
                "code": -1,
                "message": 'Body format error: need a json body'
            }, indent=2),200,{'Content-Type': 'application/json'}
        else:
            if not havekeys:
                return json.dumps({
                    "code": -1,
                    "message": 'Body format error: need a json body'
                }, indent=2),200,{'Content-Type': 'application/json'}

        data_json = json.load(open(data_file))

        for key in havekeys:
            data_json[key] = request.json.get(key)

        json.dump(data_json, open(data_file, 'w'), indent=2)
        return json.dumps({
            "code": 0,
            "message": "update account success",
            "accountId": accountid,
            "updatedAt": time.ctime(),
            "status": "normal"
        }, indent=2),200,{'Content-Type': 'application/json'}
    elif request.method == 'DELETE':
        os.remove(data_file)

        return json.dumps({
            "code": 0,
            "message": "delete account success"
        }, indent=2),200,{'Content-Type': 'application/json'}


@app.route('/accounts/<string:accountid>/recharge', methods=['POST'])
def accounts_recharge(accountid):

    needkeys=['amount']

    try:
        needkeys = checkkey(needkeys, request.json.keys())

    except:
        return json.dumps({
            "code": -1,
            "message": 'Body format error: need a json body and has key %s'%(needkeys)
        }, indent=2),200,{'Content-Type': 'application/json'}
    else:
        if needkeys:
            return json.dumps({
                "code": -1,
                "message": "Body format error: need a json body and has key %s" % (needkeys)
            }, indent=2),200,{'Content-Type': 'application/json'}

    data_file = os.path.join('./accounts', accountid)
    if not os.path.exists(data_file):
        return json.dumps({
            "code": -1,
            "message": "accountId [%s] is not exist" % (accountid),
            "status": "normal"
        }, indent=2),200,{'Content-Type': 'application/json'}

    data_json = json.load(open(data_file))

    recharge = request.json.get('amount')
    data_json['balance'] = recharge + data_json['balance']

    json.dump(data_json, open(data_file, 'w'), indent=2)

    return json.dumps({
        "code": 0,
        "message": "recharge success",
        "accountId": accountid,
        "balance": data_json['balance'],
        "status": "normal"
    }, indent=2),200,{'Content-Type': 'application/json'}


if __name__ == '__main__':
    print 'you may use your browser now - http://localhost:9022/'
    data_store = './accounts'
    if not os.path.exists(data_store):
        os.mkdir(data_store)
    app.run(debug=True, host='0.0.0.0', port=9022, threaded=True)
    #app.run(debug=True, host='0.0.0.0', port=9022)
